package com.h117121.fashionshop.controller;

import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtil;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.HttpHostConnectException;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.h117121.fashionshop.controller.generic.GenericController;

@Controller
@RequestMapping("/support")
public class SupportController extends GenericController {
	@RequestMapping(method = RequestMethod.GET)
	public String showPage(HttpServletRequest request) {
		try {
			String username = "customer";
			String password = "customer";

			String url = "http://localhost:5079/api/account";
			DefaultHttpClient httpClient = new DefaultHttpClient();

			String encodedAuth = Base64
					.encodeBase64String((username + ":" + password).getBytes());
			if (!url.endsWith("?"))
				url += "?";
			List<NameValuePair> params = new LinkedList<NameValuePair>();
			params.add(new BasicNameValuePair("auth", encodedAuth));
			String paramString = URLEncodedUtils.format(params, "utf-8");
			url += paramString;

			HttpGet getRequest = new HttpGet(url);
			getRequest.addHeader("accept", "application/json");
			HttpResponse httpResponse = httpClient.execute(getRequest);

			if (httpResponse.getStatusLine().getStatusCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : "
						+ httpResponse.getStatusLine().getStatusCode());
			}
			String data = IOUtil
					.toString(httpResponse.getEntity().getContent());
			httpClient.getConnectionManager().shutdown();

			JSONObject json = new JSONObject(data);
			String status = json.getString("Key");
			if (status.equals("Successful")) {
				request.getSession().setAttribute("Token",
						json.getString("Value"));
				return "SupportPage";
			} else if (status.equals("Warning")) {
				request.getSession().setAttribute("Token",
						json.getString("Value"));
				return "SupportPage";
			} else { // Fail

				// FAIL
				return "SupportPage";
			}
		} catch (HttpHostConnectException e) {
			request.getSession().setAttribute("Token", null);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}

		return "SupportPage";
	}
}
